<template>
    <el-dialog v-model="showDialog" :title="props.type=='add'?'添加公告':'修改公告'" @close="close" style="width: 30%">
            <el-form ref="dataFrom" :rules="rules" :model="form" label-width="100px" align="center">
                <el-form-item label="类型" prop="type" >
                    <el-select v-model="form.type" placeholder="请选择" :disabled="props.type=='edit'">
                        <el-option  label="图片" value="image" />
                        <el-option  label="文字" value="text" />
                    </el-select>
                </el-form-item>
                <el-form-item v-show="form.type=='text'" label="内容" prop="content">
                    <el-input v-model="form.content" />
                </el-form-item>
                    <el-upload v-show="form.type=='image'"
                            ref="uploadRef"
                            class="upload-demo"
                            action="/api/common/upload/announcement"
                            :auto-upload="false"
                            list-type="picture"
                            :before-upload="beforeUpload"
                           :on-success = onSuccess
                           :on-error = onError
                    >
                        <template #trigger>
                            <el-button type="primary">选择文件</el-button>
                        </template>

                        <el-button class="ml-3" type="success" @click="submitUpload">
                            上传
                        </el-button>

                        <template #tip>
                            <div class="el-upload__tip">
                                必须是 JPG或PNG 格式，文件大小不能大于2MB!
                            </div>
                        </template>
                    </el-upload>
                <el-image v-if="(props.type=='edit' && form.type=='image') || uploadSuccess"
                          style="width: 100px; height: 100px"
                          :preview-src-list="[form.content]"
                          :src="form.content" fit="fill" :preview-teleported="true" />
                <el-form-item label="链接" prop="link">
                    <el-input v-model="form.link" />
                </el-form-item>
                <el-form-item v-show="props.type=='edit'" label="是否有效">
                    <el-select v-model="form.valid" placeholder="请选择">
                        <el-option  label="有效" :value = 1 />
                        <el-option  label="无效" :value = 0 />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button v-show='props.type=="add"' type="primary"   @click="addAnsmt">添加</el-button>
                    <el-button v-show="props.type=='edit'" type="warning"   @click="updateAnsmt">更新</el-button>
                    <el-button @click="close" type="primary"  >取消</el-button>
                </el-form-item>
            </el-form>
    </el-dialog>
</template>

<script setup>
    import {ref,reactive,onBeforeUpdate,onUpdated} from 'vue'
    import MySelectOption from '@/components/common/MySelectOption.vue'
    import request from '@/utils/request.js'
    import { ElMessage } from 'element-plus'
    let uploadRef = ref(null)
    let dataFrom = ref(null)
    const  emits = defineEmits(['close','reload'])
    const rules = reactive({
        type: [{ required: true, message: '请输入用户名', trigger: 'blur' },],
        content: [{required: true,message: '请输入内容', trigger: 'blur'},],
    })
    let props = defineProps(['open','type','id'])
    let showDialog = ref(false)
    let form = reactive({})
    let uploadSuccess = ref(false)

    onUpdated(function () {

    if(showDialog.value == true){
        if(props.type=='edit'){
            request.get(`/api/announcement/getAnsmt/${props.id}`).then(resp => {
                for(let key in resp){
                     form[key] = resp[key]
                }
            })
        }else if(props.type=="add"){
            for(let key in form){
                delete form[key]
            }
         }
      }

    })

    function close(){
        showDialog.value = false
        dataFrom.value.resetFields()//重置表单校验
        uploadSuccess.value = false
    }

    function addAnsmt(){
        dataFrom.value.validate((valid, fields)=>{
            if(valid) {
                request.post("/api/announcement/add", form).then(resp => {
                    close()
                    emits("reload")
                    ElMessage({message: '添加成功！', type: 'success'})
                })
            }else{
                ElMessage({message: '缺少必填项！',type: 'error'})
            }
        })
    }
    function updateAnsmt(){
        dataFrom.value.validate((valid, fields)=>{
            if(valid) {
                request.post("/api/announcement/update",form).then(resp => {
                    close()
                    emits("reload")
                    ElMessage({message: '修改成功！',type: 'success'})
                })
            }else{
                ElMessage({message: '缺少必填项！',type: 'error'})
            }
        })
    }
    const beforeUpload = (rawFile) => {
        if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
            ElMessage.error('必须是 JPG或PNG 格式!')
            return false
        } else if (rawFile.size / 1024 / 1024 > 2) {
            ElMessage.error('文件大小不能大于2MB!')
            return false
        }
        return true
    }

    function submitUpload(){
        uploadRef.value.submit()
    }
    function onSuccess(response, uploadFile, uploadFiles){
        console.log(response.data)
        ElMessage.success('上传成功!')
        form.content = response.data
        uploadSuccess.value = true
        uploadRef.value.clearFiles()
    }
    function onError(error, uploadFile, uploadFiles){
        console.log(error)
    }

    defineExpose({showDialog})
</script>

<style scoped>

</style>